package onework;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
import java.util.Random;

public class TeachingManagementSystemGUI extends JFrame {
    private JTabbedPane tabbedPane;
    private JPanel lessonPanel, groupPanel, studentPanel, randomPanel;
    private DefaultTableModel lessonModel, groupModel, studentModel;

    public TeachingManagementSystemGUI() {
        setTitle("教学管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        tabbedPane = new JTabbedPane();

        initLessonPanel();
        initGroupPanel();
        initStudentPanel();
        initRandomPanel();

        tabbedPane.addTab("班级管理", lessonPanel);
        tabbedPane.addTab("小组管理", groupPanel);
        tabbedPane.addTab("学生管理", studentPanel);
        tabbedPane.addTab("随机点名", randomPanel);

        add(tabbedPane);
        setLocationRelativeTo(null);
        refreshAllTables();
    }

    private void refreshAllTables() {
        refreshLessonTable();
        refreshGroupTable();
        refreshStudentTable();
    }

    private void refreshLessonTable() {
        lessonModel.setRowCount(0);
        for (Lesson lesson : Manage.lessonICO.values()) {
            lessonModel.addRow(new Object[]{lesson.classname});
        }
    }

    private void refreshGroupTable() {
        groupModel.setRowCount(0);
        for (Group group : Manage.groupICO.values()) {
            groupModel.addRow(new Object[]{
                    group.number,
                    group.member1,
                    group.member2,
                    group.score
            });
        }
    }

    private void refreshStudentTable() {
        studentModel.setRowCount(0);
        for (Student student : Manage.studentICO.values()) {
            studentModel.addRow(new Object[]{
                    student.number,
                    student.name,
                    student.grade,
                    student.team,
                    student.attendance,
                    student.reply,
                    student.grades
            });
        }
    }

    private void initLessonPanel() {
        lessonPanel = new JPanel(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增班级");
        JButton editButton = new JButton("修改班级");
        JButton deleteButton = new JButton("删除班级");
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        String[] columns = {"班级名称"};
        lessonModel = new DefaultTableModel(columns, 0);
        JTable table = new JTable(lessonModel);
        JScrollPane scrollPane = new JScrollPane(table);

        lessonPanel.add(buttonPanel, BorderLayout.NORTH);
        lessonPanel.add(scrollPane, BorderLayout.CENTER);

        addButton.addActionListener(e -> {
            String className = JOptionPane.showInputDialog("请输入班级名称：");
            if (className != null && !className.trim().isEmpty()) {
                Lesson lesson = new Lesson();
                lesson.classname = className;
                Manage.lessonICO.put(className, lesson);
                refreshLessonTable();
            }
        });

        editButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String oldName = (String)lessonModel.getValueAt(row, 0);
                String newName = JOptionPane.showInputDialog("请输入新的班级名称：", oldName);
                if (newName != null && !newName.trim().isEmpty()) {
                    Lesson lesson = Manage.lessonICO.remove(oldName);
                    lesson.classname = newName;
                    Manage.lessonICO.put(newName, lesson);
                    refreshLessonTable();
                }
            }
        });

        deleteButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String className = (String)lessonModel.getValueAt(row, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除班级 " + className + " 吗？",
                        "确认删除",
                        JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    Manage.lessonICO.remove(className);
                    refreshLessonTable();
                }
            }
        });
    }

    private void initGroupPanel() {
        groupPanel = new JPanel(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增小组");
        JButton editButton = new JButton("修改小组");
        JButton deleteButton = new JButton("删除小组");
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        String[] columns = {"小组序号", "成员1", "成员2", "分数"};
        groupModel = new DefaultTableModel(columns, 0);
        JTable table = new JTable(groupModel);
        JScrollPane scrollPane = new JScrollPane(table);

        groupPanel.add(buttonPanel, BorderLayout.NORTH);
        groupPanel.add(scrollPane, BorderLayout.CENTER);

        addButton.addActionListener(e -> {
            JPanel panel = new JPanel(new GridLayout(4, 2));
            panel.add(new JLabel("小组序号:"));
            JTextField numberField = new JTextField();
            panel.add(numberField);
            panel.add(new JLabel("成员1:"));
            JTextField member1Field = new JTextField();
            panel.add(member1Field);
            panel.add(new JLabel("成员2:"));
            JTextField member2Field = new JTextField();
            panel.add(member2Field);
            panel.add(new JLabel("分数:"));
            JTextField scoreField = new JTextField();
            panel.add(scoreField);

            int result = JOptionPane.showConfirmDialog(null, panel, "新增小组",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (result == JOptionPane.OK_OPTION) {
                String groupNumber = numberField.getText().trim();

                // 检查小组序号是否已存在
                if (Manage.groupICO.containsKey(groupNumber)) {
                    JOptionPane.showMessageDialog(this,
                            "小组序号 " + groupNumber + " 已存在，请使用其他序号！",
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                Group group = new Group();
                group.number = groupNumber;
                group.member1 = member1Field.getText();
                group.member2 = member2Field.getText();
                group.score = scoreField.getText();
                Manage.groupICO.put(group.number, group);
                refreshGroupTable();
                // 立即保存到数据库
                MySQL.saveGroupData(Manage.groupICO);
            }
        });

        editButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String number = (String)groupModel.getValueAt(row, 0);
                Group group = Manage.groupICO.get(number);

                JPanel panel = new JPanel(new GridLayout(4, 2));
                panel.add(new JLabel("小组序号:"));
                JTextField numberField = new JTextField(group.number);
                panel.add(numberField);
                panel.add(new JLabel("成员1:"));
                JTextField member1Field = new JTextField(group.member1);
                panel.add(member1Field);
                panel.add(new JLabel("成员2:"));
                JTextField member2Field = new JTextField(group.member2);
                panel.add(member2Field);
                panel.add(new JLabel("分数:"));
                JTextField scoreField = new JTextField(group.score);
                panel.add(scoreField);

                int result = JOptionPane.showConfirmDialog(null, panel, "修改小组",
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                if (result == JOptionPane.OK_OPTION) {
                    Manage.groupICO.remove(number);
                    group.number = numberField.getText();
                    group.member1 = member1Field.getText();
                    group.member2 = member2Field.getText();
                    group.score = scoreField.getText();
                    Manage.groupICO.put(group.number, group);
                    refreshGroupTable();
                    // 立即保存到数据库
                    MySQL.saveGroupData(Manage.groupICO);
                }
            }
        });

        deleteButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String number = (String)groupModel.getValueAt(row, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除小组 " + number + " 吗？",
                        "确认删除",
                        JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    Manage.groupICO.remove(number);
                    refreshGroupTable();
                    // 立即保存到数据库
                    MySQL.saveGroupData(Manage.groupICO);
                }
            }
        });
    }

    private void initStudentPanel() {
        studentPanel = new JPanel(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增学生");
        JButton editButton = new JButton("修改学生");
        JButton deleteButton = new JButton("删除学生");
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        String[] columns = {"学号", "姓名", "班级", "小组", "考勤", "答题情况", "成绩"};
        studentModel = new DefaultTableModel(columns, 0);
        JTable table = new JTable(studentModel);
        JScrollPane scrollPane = new JScrollPane(table);

        studentPanel.add(buttonPanel, BorderLayout.NORTH);
        studentPanel.add(scrollPane, BorderLayout.CENTER);

        addButton.addActionListener(e -> {
            JPanel panel = new JPanel(new GridLayout(7, 2));
            panel.add(new JLabel("学号:"));
            JTextField numberField = new JTextField();
            panel.add(numberField);
            panel.add(new JLabel("姓名:"));
            JTextField nameField = new JTextField();
            panel.add(nameField);
            panel.add(new JLabel("班级:"));
            JTextField gradeField = new JTextField();
            panel.add(gradeField);
            panel.add(new JLabel("小组:"));
            JTextField teamField = new JTextField();
            panel.add(teamField);
            panel.add(new JLabel("考勤:"));
            JTextField attendanceField = new JTextField("0"); // 默认值为0
            panel.add(attendanceField);
            panel.add(new JLabel("答题情况:"));
            JTextField replyField = new JTextField();
            panel.add(replyField);
            panel.add(new JLabel("成绩:"));
            JTextField gradesField = new JTextField();
            panel.add(gradesField);

            int result = JOptionPane.showConfirmDialog(null, panel, "新增学生",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (result == JOptionPane.OK_OPTION) {
                try {
                    Student student = new Student();
                    student.number = numberField.getText().trim();
                    student.name = nameField.getText().trim();
                    student.grade = gradeField.getText().trim();
                    student.team = teamField.getText().trim();
                    student.attendance = attendanceField.getText().trim();
                    student.reply = replyField.getText().trim();
                    student.grades = gradesField.getText().trim();

                    // 检查必填字段
                    if (student.number.isEmpty() || student.name.isEmpty() ||
                            student.grade.isEmpty() || student.team.isEmpty()) {
                        JOptionPane.showMessageDialog(this,
                                "学号、姓名、班级和小组是必填字段！",
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    // 检查学号是否已存在
                    for (Student existingStudent : Manage.studentICO.values()) {
                        if (existingStudent.number.equals(student.number)) {
                            JOptionPane.showMessageDialog(this,
                                    "学号 " + student.number + " 已存在！",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }

                    Manage.studentICO.put(student.name, student);
                    refreshStudentTable();
                    // 立即保存到数据库
                    MySQL.saveStudentData(Manage.studentICO);

                    System.out.println("学生信息已保存到数据库");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "保存学生信息时出错：" + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        editButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String name = (String)studentModel.getValueAt(row, 1);
                Student student = Manage.studentICO.get(name);

                JPanel panel = new JPanel(new GridLayout(7, 2));
                panel.add(new JLabel("学号:"));
                JTextField numberField = new JTextField(student.number);
                panel.add(numberField);
                panel.add(new JLabel("姓名:"));
                JTextField nameField = new JTextField(student.name);
                panel.add(nameField);
                panel.add(new JLabel("班级:"));
                JTextField gradeField = new JTextField(student.grade);
                panel.add(gradeField);
                panel.add(new JLabel("小组:"));
                JTextField teamField = new JTextField(student.team);
                panel.add(teamField);
                panel.add(new JLabel("考勤:"));
                JTextField attendanceField = new JTextField(student.attendance);
                panel.add(attendanceField);
                panel.add(new JLabel("答题情况:"));
                JTextField replyField = new JTextField(student.reply);
                panel.add(replyField);
                panel.add(new JLabel("成绩:"));
                JTextField gradesField = new JTextField(student.grades);
                panel.add(gradesField);

                int result = JOptionPane.showConfirmDialog(null, panel, "修改学生",
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                if (result == JOptionPane.OK_OPTION) {
                    try {
                        Manage.studentICO.remove(name);
                        student.number = numberField.getText().trim();
                        student.name = nameField.getText().trim();
                        student.grade = gradeField.getText().trim();
                        student.team = teamField.getText().trim();
                        student.attendance = attendanceField.getText().trim();
                        student.reply = replyField.getText().trim();
                        student.grades = gradesField.getText().trim();

                        // 检查必填字段
                        if (student.number.isEmpty() || student.name.isEmpty() ||
                                student.grade.isEmpty() || student.team.isEmpty()) {
                            JOptionPane.showMessageDialog(this,
                                    "学号、姓名、班级和小组是必填字段！",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }

                        Manage.studentICO.put(student.name, student);
                        refreshStudentTable();
                        // 立即保存到数据库
                        MySQL.saveStudentData(Manage.studentICO);

                        System.out.println("学生信息已更新并保存到数据库");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(this,
                                "更新学生信息时出错：" + ex.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        deleteButton.addActionListener(e -> {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String name = (String)studentModel.getValueAt(row, 1);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除学生 " + name + " 吗？",
                        "确认删除",
                        JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    Manage.studentICO.remove(name);
                    refreshStudentTable();
                    // 立即保存到数据库
                    MySQL.saveStudentData(Manage.studentICO);
                }
            }
        });
    }

    private void initRandomPanel() {
        randomPanel = new JPanel(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        JButton randomGroupButton = new JButton("随机抽组");
        JButton randomStudentInGroupButton = new JButton("小组内随机抽人");
        JButton randomStudentInClassButton = new JButton("班级内随机抽人");
        JButton exportGradesButton = new JButton("导出成绩");

        buttonPanel.add(randomGroupButton);
        buttonPanel.add(randomStudentInGroupButton);
        buttonPanel.add(randomStudentInClassButton);
        buttonPanel.add(exportGradesButton);

        JTextArea resultArea = new JTextArea(10, 40);
        resultArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(resultArea);

        randomPanel.add(buttonPanel, BorderLayout.NORTH);
        randomPanel.add(scrollPane, BorderLayout.CENTER);

        randomGroupButton.addActionListener(e -> {
            if (Manage.groupICO.isEmpty()) {
                resultArea.setText("没有可用的组！");
                return;
            }
            String[] groups = Manage.groupICO.keySet().toArray(new String[0]);
            String randomGroup = groups[new Random().nextInt(groups.length)];
            Group group = Manage.groupICO.get(randomGroup);
            resultArea.setText("随机抽取的组：\n" +
                    "小组序号: " + group.number +
                    "\n成员1: " + group.member1 +
                    "\n成员2: " + group.member2 +
                    "\n分数: " + group.score);
        });

        randomStudentInGroupButton.addActionListener(e -> {
            String groupNumber = JOptionPane.showInputDialog("请输入小组序号：");
            if (groupNumber != null && !groupNumber.trim().isEmpty()) {
                Group group = Manage.groupICO.get(groupNumber);
                if (group != null) {
                    // 随机选择成员1或成员2
                    String selectedMember = new Random().nextBoolean() ? group.member1 : group.member2;
                    Student student = Manage.studentICO.get(selectedMember);
                    if (student != null) {
                        resultArea.setText("随机抽取的学生：\n" +
                                "学号: " + student.number +
                                "\n姓名: " + student.name +
                                "\n班级: " + student.grade +
                                "\n小组: " + student.team);

                        // 更新考勤
                        student.attendance = student.attendance + "1";

                        // 记录答题情况
                        String reply = JOptionPane.showInputDialog("请输入答题情况：");
                        if (reply != null) {
                            student.reply = reply;
                            refreshStudentTable();
                        }
                    }
                } else {
                    resultArea.setText("未找到该小组！");
                }
            }
        });

        randomStudentInClassButton.addActionListener(e -> {
            String className = JOptionPane.showInputDialog("请输入班级名称：");
            if (className != null && !className.trim().isEmpty()) {
                // 获取该班级的所有学生
                java.util.List<Student> classStudents = new java.util.ArrayList<>();
                for (Student student : Manage.studentICO.values()) {
                    if (student.grade.equals(className)) {
                        classStudents.add(student);
                    }
                }

                if (!classStudents.isEmpty()) {
                    // 随机选择一个学生
                    Student selectedStudent = classStudents.get(new Random().nextInt(classStudents.size()));
                    resultArea.setText("随机抽取的学生：\n" +
                            "学号: " + selectedStudent.number +
                            "\n姓名: " + selectedStudent.name +
                            "\n班级: " + selectedStudent.grade +
                            "\n小组: " + selectedStudent.team);

                    // 更新考勤
                    selectedStudent.attendance = selectedStudent.attendance + "1";

                    // 记录答题情况
                    String reply = JOptionPane.showInputDialog("请输入答题情况：");
                    if (reply != null) {
                        selectedStudent.reply = reply;
                        refreshStudentTable();
                    }
                } else {
                    resultArea.setText("该班级没有学生！");
                }
            }
        });
    }
} 